# -*- coding: utf-8 -*-
"""
用户管理API

提供完整的用户管理功能：
- 用户CRUD操作
- 用户状态管理
- 用户权限查看
- 用户密码管理
- 用户活动日志
"""

from typing import List, Dict, Any, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query, File, UploadFile
from sqlalchemy.orm import Session, joinedload
from sqlalchemy import and_, or_, desc, func
from pydantic import BaseModel, Field, EmailStr, validator
import logging
from datetime import datetime, timedelta
import bcrypt
import os

from ...core.database import get_db
from ...auth.jwt_auth import get_current_active_user, password_manager
from ...models.rbac import User, Role, UserRole, UserStatus, PermissionLog
from ...services.rbac_service import get_permission_manager, PermissionDecorator
from ...core.exceptions import ValidationError
from ...core.dto import ResponseDTO, ListResponseDTO, PaginationDTO

logger = logging.getLogger(__name__)
router = APIRouter()


# ==================== 数据模型 ====================

class UserCreateRequest(BaseModel):
    """创建用户请求"""
    username: str = Field(..., min_length=3, max_length=50, description="用户名")
    email: EmailStr = Field(..., description="邮箱地址")
    real_name: str = Field(..., min_length=1, max_length=50, description="真实姓名")
    password: str = Field(..., min_length=6, max_length=128, description="密码")
    phone: Optional[str] = Field(None, max_length=20, description="手机号")
    employee_id: Optional[str] = Field(None, max_length=20, description="员工编号")
    department: Optional[str] = Field(None, max_length=50, description="部门")
    position: Optional[str] = Field(None, max_length=50, description="职位")
    manager_id: Optional[int] = Field(None, description="直属领导ID")
    role_ids: Optional[List[int]] = Field(None, description="角色ID列表")
    status: Optional[UserStatus] = Field(UserStatus.ACTIVE, description="用户状态")

    @validator('username')
    def validate_username(cls, v):
        if not v.replace('_', '').replace('-', '').isalnum():
            raise ValueError('用户名只能包含字母、数字、下划线和连字符')
        return v

    @validator('phone')
    def validate_phone(cls, v):
        if v and not v.replace('-', '').replace('+', '').replace(' ', '').isdigit():
            raise ValueError('手机号格式不正确')
        return v


class UserUpdateRequest(BaseModel):
    """更新用户请求"""
    email: Optional[EmailStr] = Field(None, description="邮箱地址")
    real_name: Optional[str] = Field(None, min_length=1, max_length=50, description="真实姓名")
    phone: Optional[str] = Field(None, max_length=20, description="手机号")
    employee_id: Optional[str] = Field(None, max_length=20, description="员工编号")
    department: Optional[str] = Field(None, max_length=50, description="部门")
    position: Optional[str] = Field(None, max_length=50, description="职位")
    manager_id: Optional[int] = Field(None, description="直属领导ID")
    status: Optional[UserStatus] = Field(None, description="用户状态")


class PasswordChangeRequest(BaseModel):
    """修改密码请求"""
    old_password: str = Field(..., description="原密码")
    new_password: str = Field(..., min_length=6, max_length=128, description="新密码")
    confirm_password: str = Field(..., description="确认新密码")

    @validator('confirm_password')
    def passwords_match(cls, v, values):
        if 'new_password' in values and v != values['new_password']:
            raise ValueError('两次输入的密码不一致')
        return v


class PasswordResetRequest(BaseModel):
    """重置密码请求"""
    new_password: str = Field(..., min_length=6, max_length=128, description="新密码")
    send_email: bool = Field(True, description="是否发送邮件通知")


class UserBatchUpdateRequest(BaseModel):
    """批量更新用户请求"""
    user_ids: List[int] = Field(..., description="用户ID列表")
    updates: Dict[str, Any] = Field(..., description="更新字段")


# ==================== 用户管理API ====================

@router.get("/users", response_model=ResponseDTO[List[Dict]], summary="获取用户列表")
@PermissionDecorator.require_permission("system.users", "read")
async def get_users(
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user),
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    department: Optional[str] = Query(None, description="部门筛选"),
    status: Optional[UserStatus] = Query(None, description="状态筛选"),
    role_id: Optional[int] = Query(None, description="角色筛选"),
    sort_field: str = Query("created_at", description="排序字段"),
    sort_order: str = Query("desc", regex="^(asc|desc)$", description="排序方向")
):
    """获取用户列表"""
    try:
        # 构建查询
        query = db.query(User).options(
            joinedload(User.user_roles).joinedload(UserRole.role)
        )
        
        # 搜索条件
        if search:
            search_filter = or_(
                User.username.contains(search),
                User.real_name.contains(search),
                User.email.contains(search),
                User.employee_id.contains(search)
            )
            query = query.filter(search_filter)
        
        # 筛选条件
        if department:
            query = query.filter(User.department == department)
        
        if status:
            query = query.filter(User.status == status)
        
        if role_id:
            query = query.join(UserRole).filter(
                and_(UserRole.role_id == role_id, UserRole.is_active == True)
            )
        
        # 排序
        sort_column = getattr(User, sort_field, User.created_at)
        if sort_order == "desc":
            query = query.order_by(desc(sort_column))
        else:
            query = query.order_by(sort_column)
        
        # 分页
        total = query.count()
        users = query.offset((page - 1) * size).limit(size).all()
        
        # 构建响应数据
        user_list = []
        for user in users:
            user_data = {
                "id": user.id,
                "username": user.username,
                "email": user.email,
                "real_name": user.real_name,
                "employee_id": user.employee_id,
                "phone": user.phone,
                "department": user.department,
                "position": user.position,
                "status": user.status.value,
                "is_superuser": user.is_superuser,
                "is_active": user.is_active,
                "last_login_at": user.last_login_at.isoformat() if user.last_login_at else None,
                "created_at": user.created_at.isoformat(),
                "roles": [
                    {
                        "id": ur.role.id,
                        "name": ur.role.name,
                        "code": ur.role.code
                    } for ur in user.user_roles if ur.is_active and ur.role.is_active
                ]
            }
            user_list.append(user_data)
        
        return ResponseDTO[List[Dict]](
            success=True,
            message="获取用户列表成功",
            data=user_list,
            total=total,
            page=page,
            size=size
        )
        
    except Exception as e:
        logger.error(f"获取用户列表失败: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取用户列表失败"
        )


@router.get("/users/{user_id}", response_model=ResponseDTO[Dict], summary="获取用户详情")
@PermissionDecorator.require_permission("system.users", "read")
async def get_user_detail(
    user_id: int,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """获取用户详细信息"""
    try:
        user = db.query(User).options(
            joinedload(User.user_roles).joinedload(UserRole.role)
        ).filter(User.id == user_id).first()
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )
        
        # 获取用户权限信息
        permission_manager = get_permission_manager(db)
        user_permissions = permission_manager.get_user_permissions(user_id)
        
        user_data = {
            "id": user.id,
            "username": user.username,
            "email": user.email,
            "real_name": user.real_name,
            "nickname": user.nickname,
            "avatar_url": user.avatar_url,
            "employee_id": user.employee_id,
            "phone": user.phone,
            "department": user.department,
            "position": user.position,
            "manager_id": user.manager_id,
            "status": user.status.value,
            "is_superuser": user.is_superuser,
            "is_active": user.is_active,
            "last_login_at": user.last_login_at.isoformat() if user.last_login_at else None,
            "last_login_ip": user.last_login_ip,
            "login_count": user.login_count,
            "created_at": user.created_at.isoformat(),
            "updated_at": user.updated_at.isoformat(),
            "roles": [
                {
                    "id": ur.role.id,
                    "name": ur.role.name,
                    "code": ur.role.code,
                    "assigned_at": ur.created_at.isoformat(),
                    "expires_at": ur.expires_at.isoformat() if ur.expires_at else None,
                    "is_active": ur.is_active
                } for ur in user.user_roles
            ],
            "permissions": list(user_permissions)
        }
        
        return ResponseDTO[Dict](
            success=True,
            message="获取用户详情成功",
            data=user_data
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取用户详情失败: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取用户详情失败"
        )


@router.post("/users", response_model=ResponseDTO[Dict], summary="创建用户")
@PermissionDecorator.require_permission("system.users", "create")
async def create_user(
    request: UserCreateRequest,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """创建新用户"""
    try:
        # 检查用户名是否已存在
        existing_user = db.query(User).filter(
            or_(
                User.username == request.username,
                User.email == request.email,
                User.employee_id == request.employee_id if request.employee_id else False
            )
        ).first()
        
        if existing_user:
            if existing_user.username == request.username:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="用户名已存在"
                )
            elif existing_user.email == request.email:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="邮箱已存在"
                )
            elif existing_user.employee_id == request.employee_id:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="员工编号已存在"
                )
        
        # 验证管理者存在
        if request.manager_id:
            manager = db.query(User).filter(User.id == request.manager_id).first()
            if not manager:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="指定的管理者不存在"
                )
        
        # 创建用户
        password_hash = password_manager.hash_password(request.password)
        
        user = User(
            username=request.username,
            email=request.email,
            real_name=request.real_name,
            phone=request.phone,
            employee_id=request.employee_id,
            department=request.department,
            position=request.position,
            manager_id=request.manager_id,
            password_hash=password_hash,
            status=request.status,
            created_by=current_user["user_id"]
        )
        
        db.add(user)
        db.flush()  # 获取用户ID
        
        # 分配角色
        if request.role_ids:
            for role_id in request.role_ids:
                # 验证角色存在
                role = db.query(Role).filter(Role.id == role_id).first()
                if role and role.is_active:
                    user_role = UserRole(
                        user_id=user.id,
                        role_id=role_id,
                        assigned_by=current_user["user_id"]
                    )
                    db.add(user_role)
        
        db.commit()
        db.refresh(user)
        
        # 记录操作日志
        log_entry = PermissionLog(
            operation_type="CREATE",
            target_type="USER",
            target_id=user.id,
            operation_desc=f"创建用户: {user.username}",
            operator_id=current_user["user_id"]
        )
        db.add(log_entry)
        db.commit()
        
        user_data = {
            "id": user.id,
            "username": user.username,
            "email": user.email,
            "real_name": user.real_name,
            "employee_id": user.employee_id,
            "status": user.status.value,
            "created_at": user.created_at.isoformat()
        }
        
        logger.info(f"创建用户成功: {user.username}, 操作人: {current_user['username']}")
        
        return ResponseDTO[Dict](
            success=True,
            message="创建用户成功",
            data=user_data
        )
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logger.error(f"创建用户失败: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="创建用户失败"
        )


@router.put("/users/{user_id}", response_model=ResponseDTO[Dict], summary="更新用户")
@PermissionDecorator.require_permission("system.users", "update")
async def update_user(
    user_id: int,
    request: UserUpdateRequest,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """更新用户信息"""
    try:
        user = db.query(User).filter(User.id == user_id).first()
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )
        
        # 记录更新前数据
        before_data = {
            "email": user.email,
            "real_name": user.real_name,
            "phone": user.phone,
            "employee_id": user.employee_id,
            "department": user.department,
            "position": user.position,
            "manager_id": user.manager_id,
            "status": user.status.value
        }
        
        # 检查邮箱唯一性
        if request.email and request.email != user.email:
            existing_email = db.query(User).filter(
                and_(User.email == request.email, User.id != user_id)
            ).first()
            if existing_email:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="邮箱已存在"
                )
        
        # 检查员工编号唯一性
        if request.employee_id and request.employee_id != user.employee_id:
            existing_employee = db.query(User).filter(
                and_(User.employee_id == request.employee_id, User.id != user_id)
            ).first()
            if existing_employee:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="员工编号已存在"
                )
        
        # 验证管理者存在
        if request.manager_id and request.manager_id != user.manager_id:
            if request.manager_id == user_id:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="不能将自己设为管理者"
                )
            manager = db.query(User).filter(User.id == request.manager_id).first()
            if not manager:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="指定的管理者不存在"
                )
        
        # 更新字段
        update_fields = []
        for field, value in request.dict(exclude_unset=True).items():
            if hasattr(user, field) and getattr(user, field) != value:
                setattr(user, field, value)
                update_fields.append(field)
        
        if update_fields:
            user.updated_by = current_user["user_id"]
            db.commit()
            db.refresh(user)
            
            # 记录操作日志
            after_data = {field: getattr(user, field) for field in before_data.keys()}
            log_entry = PermissionLog(
                operation_type="UPDATE",
                target_type="USER",
                target_id=user.id,
                before_data=str(before_data),
                after_data=str(after_data),
                operation_desc=f"更新用户信息: {', '.join(update_fields)}",
                operator_id=current_user["user_id"]
            )
            db.add(log_entry)
            db.commit()
        
        user_data = {
            "id": user.id,
            "username": user.username,
            "email": user.email,
            "real_name": user.real_name,
            "employee_id": user.employee_id,
            "phone": user.phone,
            "department": user.department,
            "position": user.position,
            "manager_id": user.manager_id,
            "status": user.status.value,
            "updated_at": user.updated_at.isoformat()
        }
        
        logger.info(f"更新用户成功: {user.username}, 操作人: {current_user['username']}")
        
        return ResponseDTO[Dict](
            success=True,
            message="更新用户成功",
            data=user_data
        )
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logger.error(f"更新用户失败: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="更新用户失败"
        )


@router.delete("/users/{user_id}", response_model=ResponseDTO[Dict], summary="删除用户")
@PermissionDecorator.require_permission("system.users", "delete")
async def delete_user(
    user_id: int,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user),
    hard_delete: bool = Query(False, description="是否硬删除")
):
    """删除用户"""
    try:
        user = db.query(User).filter(User.id == user_id).first()
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )
        
        # 不能删除自己
        if user_id == current_user["user_id"]:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="不能删除自己"
            )
        
        # 不能删除超级用户（除非当前用户也是超级用户）
        if user.is_superuser and not current_user.get("is_superuser", False):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="无权限删除超级用户"
            )
        
        if hard_delete:
            # 硬删除：直接删除记录
            db.delete(user)
            operation_desc = f"硬删除用户: {user.username}"
        else:
            # 软删除：标记为已删除状态
            user.status = UserStatus.DELETED
            user.is_active = False
            user.updated_by = current_user["user_id"]
            operation_desc = f"软删除用户: {user.username}"
        
        db.commit()
        
        # 记录操作日志
        log_entry = PermissionLog(
            operation_type="DELETE",
            target_type="USER",
            target_id=user_id,
            operation_desc=operation_desc,
            operator_id=current_user["user_id"]
        )
        db.add(log_entry)
        db.commit()
        
        logger.info(f"删除用户成功: {user.username}, 操作人: {current_user['username']}")
        
        return ResponseDTO[Dict](
            success=True,
            message="删除用户成功",
            data={"user_id": user_id, "hard_delete": hard_delete}
        )
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logger.error(f"删除用户失败: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="删除用户失败"
        )


# ==================== 用户状态管理API ====================

@router.post("/users/{user_id}/activate", response_model=ResponseDTO[Dict], summary="激活用户")
@PermissionDecorator.require_permission("system.users", "manage")
async def activate_user(
    user_id: int,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """激活用户"""
    try:
        user = db.query(User).filter(User.id == user_id).first()
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )
        
        user.status = UserStatus.ACTIVE
        user.is_active = True
        user.locked_until = None
        user.login_attempts = 0
        user.updated_by = current_user["user_id"]
        
        db.commit()
        
        # 记录操作日志
        log_entry = PermissionLog(
            operation_type="ACTIVATE",
            target_type="USER",
            target_id=user_id,
            operation_desc=f"激活用户: {user.username}",
            operator_id=current_user["user_id"]
        )
        db.add(log_entry)
        db.commit()
        
        return ResponseDTO[Dict](
            success=True,
            message="用户激活成功",
            data={"user_id": user_id, "status": user.status.value}
        )
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logger.error(f"激活用户失败: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="激活用户失败"
        )


@router.post("/users/{user_id}/suspend", response_model=ResponseDTO[Dict], summary="暂停用户")
@PermissionDecorator.require_permission("system.users", "manage")
async def suspend_user(
    user_id: int,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user),
    reason: str = Query(..., description="暂停原因")
):
    """暂停用户"""
    try:
        user = db.query(User).filter(User.id == user_id).first()
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )
        
        # 不能暂停自己
        if user_id == current_user["user_id"]:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="不能暂停自己"
            )
        
        user.status = UserStatus.SUSPENDED
        user.is_active = False
        user.updated_by = current_user["user_id"]
        
        db.commit()
        
        # 记录操作日志
        log_entry = PermissionLog(
            operation_type="SUSPEND",
            target_type="USER",
            target_id=user_id,
            operation_desc=f"暂停用户: {user.username}, 原因: {reason}",
            operator_id=current_user["user_id"]
        )
        db.add(log_entry)
        db.commit()
        
        return ResponseDTO[Dict](
            success=True,
            message="用户暂停成功",
            data={"user_id": user_id, "status": user.status.value}
        )
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logger.error(f"暂停用户失败: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="暂停用户失败"
        )


@router.post("/users/{user_id}/lock", response_model=ResponseDTO[Dict], summary="锁定用户")
@PermissionDecorator.require_permission("system.users", "manage")
async def lock_user(
    user_id: int,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user),
    reason: str = Query(..., description="锁定原因"),
    lock_duration_hours: Optional[int] = Query(None, description="锁定时长(小时)，不填表示永久锁定")
):
    """锁定用户"""
    try:
        user = db.query(User).filter(User.id == user_id).first()
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )
        
        # 不能锁定自己
        if user_id == current_user["user_id"]:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="不能锁定自己"
            )
        
        user.status = UserStatus.LOCKED
        user.is_active = False
        
        # 设置锁定时间
        if lock_duration_hours:
            user.locked_until = datetime.utcnow() + timedelta(hours=lock_duration_hours)
        else:
            user.locked_until = None  # 永久锁定
            
        user.updated_by = current_user["user_id"]
        
        db.commit()
        
        # 记录操作日志
        log_entry = PermissionLog(
            operation_type="LOCK",
            target_type="USER",
            target_id=user_id,
            operation_desc=f"锁定用户: {user.username}, 原因: {reason}, 时长: {lock_duration_hours or '永久'}小时",
            operator_id=current_user["user_id"]
        )
        db.add(log_entry)
        db.commit()
        
        return ResponseDTO[Dict](
            success=True,
            message="用户锁定成功",
            data={
                "user_id": user_id, 
                "status": user.status.value,
                "locked_until": user.locked_until.isoformat() if user.locked_until else None
            }
        )
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logger.error(f"锁定用户失败: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="锁定用户失败"
        )


# ==================== 密码管理API ====================

@router.post("/users/{user_id}/reset-password", response_model=ResponseDTO[Dict], summary="重置用户密码")
@PermissionDecorator.require_permission("system.users", "manage")
async def reset_user_password(
    user_id: int,
    request: PasswordResetRequest,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """重置用户密码"""
    try:
        user = db.query(User).filter(User.id == user_id).first()
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )
        
        # 更新密码
        password_hash = password_manager.hash_password(request.new_password)
        user.password_hash = password_hash
        user.password_updated_at = datetime.utcnow()
        user.login_attempts = 0
        user.locked_until = None
        user.updated_by = current_user["user_id"]
        
        db.commit()
        
        # 记录操作日志
        log_entry = PermissionLog(
            operation_type="RESET_PASSWORD",
            target_type="USER",
            target_id=user_id,
            operation_desc=f"重置用户密码: {user.username}",
            operator_id=current_user["user_id"]
        )
        db.add(log_entry)
        db.commit()
        
        # TODO: 发送邮件通知（如果启用）
        if request.send_email:
            # await send_password_reset_email(user.email, request.new_password)
            pass
        
        return ResponseDTO[Dict](
            success=True,
            message="密码重置成功",
            data={"user_id": user_id, "email_sent": request.send_email}
        )
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logger.error(f"重置密码失败: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="重置密码失败"
        )


# ==================== 用户统计API ====================

@router.get("/users/statistics", response_model=ResponseDTO[Dict], summary="获取用户统计信息")
@PermissionDecorator.require_permission("system.users", "read")
async def get_user_statistics(
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """获取用户统计信息"""
    try:
        # 基本统计（按照模块文档2.1要求的4种状态）
        total_users = db.query(User).count()
        active_users = db.query(User).filter(User.status == UserStatus.ACTIVE).count()
        locked_users = db.query(User).filter(User.status == UserStatus.LOCKED).count()
        suspended_users = db.query(User).filter(User.status == UserStatus.SUSPENDED).count()
        deleted_users = db.query(User).filter(User.status == UserStatus.DELETED).count()
        
        # 部门分布
        department_stats = db.query(
            User.department,
            func.count(User.id).label('count')
        ).filter(User.department.isnot(None)).group_by(User.department).all()
        
        # 最近登录统计（最近30天内有登录的用户）
        thirty_days_ago = datetime.utcnow() - timedelta(days=30)
        recent_active_users = db.query(User).filter(
            User.last_login_at >= thirty_days_ago
        ).count()
        
        # 角色分布
        role_stats = db.query(
            Role.name,
            func.count(UserRole.user_id).label('count')
        ).join(UserRole).filter(
            UserRole.is_active == True
        ).group_by(Role.id, Role.name).all()
        
        statistics = {
            "user_counts": {
                "total": total_users,
                "active": active_users,
                "locked": locked_users,
                "suspended": suspended_users,
                "deleted": deleted_users,
                "recent_active": recent_active_users
            },
            "department_distribution": [
                {"department": dept, "count": count} 
                for dept, count in department_stats
            ],
            "role_distribution": [
                {"role": role_name, "count": count}
                for role_name, count in role_stats
            ]
        }
        
        return ResponseDTO[Dict](
            success=True,
            message="获取用户统计成功",
            data=statistics
        )
        
    except Exception as e:
        logger.error(f"获取用户统计失败: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取用户统计失败"
        )